
<template>
  <div class="trackBox">
    <div class="map" v-loading="loading">
      <div id="groundMap" style="width:100%;height:100%;"></div>
    </div>
  </div>
</template>
<script>
// import BMap from 'BMap'
import $ from 'jquery'
import carUrl from '@/assets/images/ground/carIcon/car.png'
import startUrl from '@/assets/images/ground/carIcon/start.png'
import endUrl from '@/assets/images/ground/carIcon/end.png'
import tjdUrl from '@/assets/images/ground/carIcon/tjd.png'
import {getWayMap,equipmentMap} from '@/request/api'
export default {
  data () {
    return {
      token: '',
      mapData: [],
      loading: false,
      deviceNumber:this.equipment,
      plateNumber: this.childMsg,
      startTime: this.groundStartTime,
      endTime: this.groundEndTime
    }
  },
  mounted () {
    this.initMap()
  },
  props: ['groundStartTime', 'groundEndTime', 'childMsg','equipment'],
  methods: {
    search_step2 () {
      this.initMap()
      this.deviceNumber = this.equipment
      this.plateNumber = this.childMsg
      this.startTime = this.groundStartTime
      this.endTime = this.groundEndTime
      if (
        // this.plateNumber === '' ||
        this.startTime === '' ||
        this.endTime === ''
        // this.plateNumber === undefined ||
        // this.startTime === undefined ||
        // this.endTime === undefined
      ) {
        this.$message({
          message: '请将车牌号及起始时间填写完整！',
          type: 'error',
          showClose: true
        })
        return false
      }
      var _this = this
      var startTime = new Date(_this.startTime)
      var endTime = new Date(_this.endTime)
      var hours = _this.getIntervalHour(startTime, endTime)
      if (hours > 24) {
        _this.$message({
          message: '查询轨迹开始与结束之间不能大于24小时！',
          type: 'error',
          showClose: true
        })
        return false
      }
      this.getMapPoint()
    },
    getCookie (cName) {
      if (document.cookie.length > 0) {
        var cStart = document.cookie.indexOf(cName + '=')
        if (cStart !== -1) {
          cStart = cStart + cName.length + 1
          var cEnd = document.cookie.indexOf(';', cStart)
          if (cEnd === -1) cEnd = document.cookie.length
          return unescape(document.cookie.substring(cStart, cEnd))
        }
      }
      return ''
    },
    getIntervalHour (startDate, endDate) {
      var ms = endDate.getTime() - startDate.getTime()
      if (ms < 0) return 0
      return Math.floor(ms / 1000 / 60 / 60)
    },
    formatTen (num) {
      return num > 9 ? num + '' : '0' + num
    },
    formatDate (date) {
      date = new Date(date)
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var day = date.getDate()
      var hour = date.getHours()
      if (hour < 10) {
        hour = '0' + hour
      }
      var minute = date.getMinutes()
      if (minute < 10) {
        minute = '0' + minute
      }
      var second = date.getSeconds()
      if (second < 10) {
        second = '0' + second
      }
      return (
        year +
        '-' +
        this.formatTen(month) +
        '-' +
        this.formatTen(day) +
        ' ' +
        hour +
        ':' +
        minute +
        ':' +
        second
      )
    },
    getMapPoint () {
      var _this = this
        equipmentMap({
            terminalNo:this.deviceNumber,
            vcln: this.plateNumber,
            btime:this.formatDate(this.startTime),
            etime:this.formatDate(this.endTime),
        }).then(res=>{
          var dataList = res
          dataList['result'] = res.data
          if (res.success == "1") {
            var getMapData = []
            dataList.result.forEach(item => {
              getMapData.push({
                receiveTime: '20190524  13:08:47',
                alertInfomation: '',
                positionDescribe: '',
                positionTime: item.gtm,
                directionOfVehicle: item.agl,
                speed: item.spd,
                latitudeDegree: (item.lat / 600000).toFixed(6),
                longitudeDegree: (item.lon / 600000).toFixed(6),
                vehicleStatus: '0'
              })
            })
            _this.creatMap(getMapData)
         }else{
            _this.$message({
              type: 'error',
              showClose: true,
              message: '数据查询失败'
            })
         }
        }) 
    },
    initMap () {
      var map = new BMap.Map('groundMap')
      // map.centerAndZoom('武汉', 7)
      map.centerAndZoom(new BMap.Point(108.37, 22.82), 11);
      map.enableScrollWheelZoom(true)
      window.map = map
      this.addMapControl()
    },
    addMapControl () {
      // eslint-disable-next-line
      var ctrlNav = new BMap.NavigationControl({
        anchor: BMAP_ANCHOR_TOP_LEFT,
        type: BMAP_NAVIGATION_CONTROL_LARGE
      })
      window.map.addControl(ctrlNav) // 向地图中添加缩放控件
      var ctrlSca = new BMap.ScaleControl({ anchor: window.BMAP_ANCHOR_BOTTOM_LEFT })
      window.map.addControl(ctrlSca) // 向地图中添加比例尺控件
    },
    creatMap (pointsArr) {
      var points = []
      var mapData = pointsArr
      for (var i = 0; i < mapData.length; i++) {
        var p1 = mapData[i].latitudeDegree
        var p2 = mapData[i].longitudeDegree
        points.push(new BMap.Point(p2, p1))
      }
      var first = points[0]
      var last = points[points.length - 1]
      window.map.clearOverlays()
      var polyline = new BMap.Polyline(points, {
        enableEditing: false, // 是否启用线编辑，默认为false
        enableClicking: true, // 是否响应点击事件，默认为true
        strokeWeight: '5', // 折线的宽度，以像素为单位
        strokeOpacity: 0.8, // 折线的透明度，取值范围0 - 1
        strokeColor: '#18a45b' // 折线颜色
      })
      window.map.panTo(last)
      window.map.centerAndZoom('', 8)
      window.map.addOverlay(polyline) // 增加折线

      var carIcon = new BMap.Icon(carUrl, new BMap.Size(82,-20)) // 设置车辆图标大小位置
          carIcon.setImageSize(new BMap.Size(50,20));

      var startIcon = new BMap.Icon(startUrl, new BMap.Size(27, 27)) //设置起点图标大小位置
      var endIcon = new BMap.Icon(endUrl, new BMap.Size(27, 27)) // 设置终点图标大小位置
      //循坏创建标注并生成弹窗内容
      for (var i = 0; i < mapData.length; i++) {
        let pointNumber = new BMap.Point(mapData[i].longitudeDegree,mapData[i].latitudeDegree)
        var tjdIcon = new BMap.Icon(tjdUrl, new BMap.Size(40,70)) //设置途径点图标大小位置
        var car3 = new BMap.Marker(pointNumber, { icon: tjdIcon }) // 创建途径点标注
            window.map.addOverlay(car3)
          var msg = '车牌号：' +
            this.plateNumber +
            '</br>' +
            '速度&nbsp&nbsp&nbsp&nbsp：' +
            mapData[i].speed +
            '</br>' +
            '方向&nbsp&nbsp&nbsp&nbsp：' +
            mapData[i].directionOfVehicle +
            '</br>' +
            '经度&nbsp&nbsp&nbsp&nbsp：' +
            mapData[i].longitudeDegree +
            '</br>' +
            '纬度&nbsp&nbsp&nbsp&nbsp：' +
            mapData[i].latitudeDegree +
            '</br>' +
            '定位时间：' +
            mapData[i].positionTime +
            '</br>' +
            '所在地址：' +
            mapData[i].positionDescribe +
            '</br>'
        this.markerFun(car3,msg)
      }  
      var car1 = new BMap.Marker(first, { icon: carIcon }) // 创建车辆标注
      var car2 = new BMap.Marker(last, { icon: carIcon }) // 创建车辆标注
      var start = new BMap.Marker(first, { icon: startIcon }) // 创建起点标注
      var end = new BMap.Marker(last, { icon: endIcon }) // 创建终点标注
      window.map.addOverlay(car1)
      window.map.addOverlay(car2)
      window.map.addOverlay(start)
      window.map.addOverlay(end)
      this.loading = false
    },
    //点击标注，创建信息窗口
    markerFun(car3,msg){
      car3.addEventListener('click', function (e) {
        var opts = {
            width: 230, // 信息窗口宽度
            height: 150, // 信息窗口高度
            title: '车辆定位信息', // 信息窗口标题
            enableMessage: true // 设置不允许信息窗发送短息
          }
          var p = e.target;
          var point = new BMap.Point(p.point.lng, p.point.lat); 
          var infoWindow = new BMap.InfoWindow(msg, opts) // 创建信息窗口对象
          window.map.openInfoWindow(infoWindow,point) // 开启信息窗口
      })  
    },

  // 另外一种实现方法，但是有BUG,弹窗内容都是一样的
    // markerFun(points,pointsArr){
    //        var msg =
    //         // '车牌号：' +
    //         // this.plateNumber +
    //         // '</br>' +
    //         '速度&nbsp&nbsp&nbsp&nbsp：' +
    //         pointsArr[item].speed +
    //         '</br>' +
    //         '方向&nbsp&nbsp&nbsp&nbsp：' +
    //         pointsArr[item].directionOfVehicle +
    //         '</br>' +
    //         '经度&nbsp&nbsp&nbsp&nbsp：' +
    //         pointsArr[item].longitudeDegree +
    //         '</br>' +
    //         '纬度&nbsp&nbsp&nbsp&nbsp：' +
    //         pointsArr[item].latitudeDegree +
    //         '</br>' +
    //         '定位时间：' +
    //         pointsArr[item].positionTime +
    //         '</br>' +
    //         '所在地址：' +
    //         pointsArr[item].positionDescribe +
    //         '</br>'
              
    //     var tjdIcon = new BMap.Icon(tjdUrl, new BMap.Size(40,70)) //设置途径点图标大小位置
    //     var car3 = new BMap.Marker(points, { icon: tjdIcon }) // 创建途径点标注
    //         window.map.addOverlay(car3)
    //       var opts = {
    //         width: 230, // 信息窗口宽度
    //         height: 150, // 信息窗口高度
    //         title: '车辆定位信息', // 信息窗口标题
    //         enableMessage: true // 设置不允许信息窗发送短息
    //       }
      
    //       var infoWindow = new BMap.InfoWindow(msg, opts) // 创建信息窗口对象
    //         car3.addEventListener('click', function () {
    //           window.map.openInfoWindow(infoWindow,points) // 开启信息窗口
    //         })  

    // },
 
  }
}
</script>
<style lang='scss' scoped>
.searchWrapper {
  position: absolute;
  z-index: 99999999999;
  left: 5%;
  top: 10%;
}
.trackBox {
  width: 100%;
  height: 100%;
}
.map {
  height: 100%;
  z-index: 999 !important;
}
#groundMap {
  z-index: 2 !important;
}
@import "@/assets/css/transportRight.scss";
.searchEara {
  float: left;
}
.search {
  border: none;
}
ul.table {
  overflow: hidden;
  border-bottom: 1px solid #ccc;
}
.table li:first-child {
  border-left: 1px solid #ccc;
}
ul.table li {
  float: left;
  width: 25%;
  font-size: 1.4rem;
  border-right: 1px solid #ccc;
  line-height: 40px;
  height: 40px;
  text-align: center;
}
.table1 {
  background-color: #434343;
  color: #fff;
  margin-bottom: none;
}
</style>
